/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* eslint-disable max-len */
import { computed, ref, Ref, SetupContext } from 'vue';
import { AvatarProps } from '../avatar.props';
import { UseImage } from './types';

export function useImage(props: AvatarProps, context: SetupContext, fileInput: any, modelValue: Ref<string>): UseImage {
    const defaultImage =
        '';
    const errorImage =
        '';

    const readonly = ref(props.readonly);

    // 判断是否是图片路径
    function isUrl(url: string) {
        return url.match(/\.(jpeg|jpg|gif|png|svg|bmp|webp)$/) != null;
    }

    // 判断是否是完成base64
    function isBase64Image(url: string) {
        return url.indexOf('data:image/') > -1;
    }

    function appendBase64ImageHeader(val: string) {
        if (!val) {
            return '';
        }
        return 'data:image/jpeg;base64,' + val;
    }

    const acceptTypes = computed(() => {
        if (!props.type || !props.type.length) {
            return '';
        }
        const imageTypesArray = props.type.map((fileType: string) => {
            if (fileType === 'jpg') {
                fileType = 'jpeg';
            }
            return `image/${fileType}`;
        });
        if (!imageTypesArray || !imageTypesArray.length) {
            return 'image/*';
        }
        return imageTypesArray.join(',');
    });

    const imageSource = computed(() => {
        const image = modelValue.value || props.cover || defaultImage;
        if (isUrl(image) || isBase64Image(image)) {
            return image;
        }
        return appendBase64ImageHeader(image);
    });

    const imageTitle = computed(() => {
        return readonly.value ? '' : props.tile;
    });

    function onClickImage() {
        if (readonly.value) {
            return;
        }
        fileInput && fileInput.value && fileInput.value.click();
    }

    function getImageFile() {
        // return this.imgFileObj;
    }

    return { acceptTypes, imageSource, imageTitle, onClickImage };
}
